package hu.u_szeged.inf.ovrt.filelister.commands;

import static hu.u_szeged.inf.ovrt.filelister.core.beans.Colors.ERROR;
import static hu.u_szeged.inf.ovrt.filelister.core.beans.Colors.INFO;
import hu.u_szeged.inf.ovrt.filelister.core.beans.ApplicationState;
import hu.u_szeged.inf.ovrt.filelister.ui.UserInterface;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Add filter module.
 */

public class Addfilter extends AbstractCommand {

    /**
     * Constructor, that sets user interface.
     * @param ui user interface.
     */

    public Addfilter(UserInterface ui) {
        super(ui);
    }

    @Override
    public void execute(ApplicationState state, Map<String, String> parameters) {
        String parameter = null;
        String parameterTemp = null;
        Pattern pattern = Pattern.compile("[/:“<>|]");

        if (parameters.containsKey("default")) {

            parameter = parameters.get("default");
            parameterTemp = parameter;
            parameter = parameter.replace("\\", "/");
            parameter = parameter.replace(".", "\\.");
            parameter = parameter.replace("?", ".");
            parameter = parameter.replace("*", ".*");

            Matcher matcher = pattern.matcher(parameter);
            boolean result = matcher.find();
            if (!result) {
                if (!state.getFilters().contains(parameter)) {
                    this.getUi().printLn("Filter added: " + parameterTemp, INFO);
                    state.addFilter(parameter);
                } else {
                    getUi().printLn("Filter \"" + parameterTemp + "\" already exists: ", ERROR);
                }
            }
        }

        // TODO Auto-generated method stub
    }
}
